package com.easycms.framework.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author yushuo
 * @className
 * @descripton 自定义拦截器
 * @date 2021/1/27 10:00
 **/
@Component
public class EasyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在 controller 方法之前调用
        response.addHeader("easycms-version","0.0.1");

//
//        if (!(handler instanceof HandlerMethod)){
//            return true;
//        }
//        //用来判断请求是view还是json
//        HandlerMethod hm = (HandlerMethod) handler;
//        Method method = hm.getMethod();
//        // 判断返回值是否为字符串
//        boolean isString = method.getReturnType().equals(String.class);
//        // 判断方法是否使用 @ResponseBody
//        boolean isResonseBody = !method.isAnnotationPresent(ResponseBody.class);
//        // 判断方法是否使用 @RestController注解
//        boolean isRestController = !hm.getBeanType().isAnnotationPresent(RestController.class);
//        request.setAttribute("method_return_is_view",isString && isResonseBody && isRestController);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在 controller 方法之后调用
        response.addHeader("easycms-version","0.0.1=");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在 postHandle 方法之后调用
        response.addHeader("easycms-version","0.0.1-2");
    }
}
